package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.MyCourseTableParams;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2022/10/2 16:12
 */
@Slf4j
@Service
public class MyCourseTablesServiceImpl implements MyCourseTablesService {

    @Autowired
    XcChooseCourseMapper xcChooseCourseMapper;

    @Autowired
    XcCourseTablesMapper xcCourseTablesMapper;

    @Autowired
    ContentServiceClient contentServiceClient;

    @Autowired
    MyCourseTablesService myCourseTablesService;

    @Autowired
    MyCourseTablesServiceImpl currentProxy;

    /**
     * 添加课程
     * @param userId 用户id
     * @param courseId 课程id
     * @return
     */
    @Transactional
    @Override
        public XcChooseCourseDto addChooseCourse(String userId, Long courseId) {
            //查询课程课程发布表信息
            CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
            if (coursepublish==null){
                XueChengPlusException.cast("课程不存在");
            }
            //课程收费标准
            String charge = coursepublish.getCharge();
            //选课记录
            XcChooseCourse choiceCourse = null;

            if ("201000".equals(charge)) {//课程免费
                //添加免费课程
                choiceCourse = addFreeCourse(userId, coursepublish);
                //添加到我的课程表
                XcCourseTables xcCourseTables = addCourseTables(choiceCourse);
            } else {
                //添加收费课程
                choiceCourse = addChargeCourse(userId, coursepublish);
            }
            //获取学习资格(返回一个字符串即可)
        XcCourseTablesDto courseTablesDto = getLearningStatus(userId, courseId);
            //构造返回值
        XcChooseCourseDto xcChooseCourseDto = new XcChooseCourseDto();
        BeanUtils.copyProperties(choiceCourse,xcChooseCourseDto);
        //设置学习状态
         xcChooseCourseDto.setLearnStatus(courseTablesDto.getLearnStatus());
        return xcChooseCourseDto;
        }

    /**
     * 获取学习资格
     * @param userId
     * @param courseId
     * @return
     */
    @Override
    public XcCourseTablesDto getLearningStatus(String userId, Long courseId) {
        XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
        //查询我的课程表
        XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);
        if (xcCourseTables==null){
            xcCourseTablesDto.setLearnStatus("702002"); //没有选课或未支付
            return  xcCourseTablesDto;
        }
        boolean before = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());//查看课程是否过期
        if (before){
            BeanUtils.copyProperties(xcCourseTables,xcCourseTablesDto);
            xcCourseTablesDto.setLearnStatus("702003");//课程过期了
            return  xcCourseTablesDto;
        }else {
            BeanUtils.copyProperties(xcCourseTables,xcCourseTablesDto);
            xcCourseTablesDto.setLearnStatus("702001");//课程没有过期
            return  xcCourseTablesDto;
        }

    }

    /**
     * 保存选课成功信息
     * @param chooseCourseId
     * @return
     */
    @Override
    @Transactional
    public boolean saveChooseCourseStatus(String chooseCourseId) {
        //根据选课id查询选课表
        XcChooseCourse chooseCourse = xcChooseCourseMapper.selectById(chooseCourseId);
        if (chooseCourse==null){
            log.debug("接收到购买课程的消息，根据选课id查询不到选课记录，选课id{}",chooseCourseId);
            return  false;
        }
        //一定是待支付701002才能选课成功
        if ("701002".equals(chooseCourse.getStatus())){
            //跟新选课状态为已支付
            chooseCourse.setStatus("701001");
            int insert = xcChooseCourseMapper.insert(chooseCourse);
            if (insert<=0){
                log.debug("添加到选课表失败:{}",chooseCourse);
                XueChengPlusException.cast("添加到选课记录失败");
            }
        }
        //向我的课程表插入选课成功记录   添加事务代理
        XcCourseTables CourseTables = currentProxy.addCourseTables(chooseCourse);

        return true;
    }

    /**
     * 个人中心分页查询
     * @param params
     * @return
     */
    @Override
    public PageResult<XcCourseTables> mycourestabls(MyCourseTableParams params) {
        //分页参数
        String userId = params.getUserId();
        int pageSize=params.getSize();
        int pageNo=params.getPage();
        Page<XcCourseTables> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<XcCourseTables> lambdaQueryWrapper = new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId, userId);

        //查询条件
        Page<XcCourseTables> xcCourseTablesPage = xcCourseTablesMapper.selectPage(page, lambdaQueryWrapper);
        //数据列表
        List<XcCourseTables> records = xcCourseTablesPage.getRecords();
        long total = xcCourseTablesPage.getTotal();
        //总记录数
        PageResult<XcCourseTables> pageResult = new PageResult<>(records, total, pageNo, pageSize);

        return pageResult;
    }

    //添加免费课程到选课记录表
        public XcChooseCourse addFreeCourse(String userId, CoursePublish coursepublish) {
            //查询选课记录表是否存在免费的且选课成功的订单
            LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper = queryWrapper.eq(XcChooseCourse::getUserId, userId)
                    .eq(XcChooseCourse::getCourseId, coursepublish.getId())
                    .eq(XcChooseCourse::getOrderType, "700001")//免费课程
                    .eq(XcChooseCourse::getStatus, "701001");//选课成功
            List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);
            if (xcChooseCourses != null && xcChooseCourses.size()>0) {
                return xcChooseCourses.get(0);
            }
            //添加选课记录信息
            XcChooseCourse xcChooseCourse = new XcChooseCourse();
            xcChooseCourse.setCourseId(coursepublish.getId());
            xcChooseCourse.setCourseName(coursepublish.getName());
            xcChooseCourse.setCoursePrice(0f);//免费课程价格为0
            xcChooseCourse.setUserId(userId);
            xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
            xcChooseCourse.setOrderType("700001");//免费课程
            xcChooseCourse.setCreateDate(LocalDateTime.now());
            xcChooseCourse.setStatus("701001");//选课成功

            xcChooseCourse.setValidDays(365);//免费课程默认365
            xcChooseCourse.setValidtimeStart(LocalDateTime.now());
            xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
            int insert = xcChooseCourseMapper.insert(xcChooseCourse);
            if (insert<=0){
                XueChengPlusException.cast("添加选课失败");
            }

            return xcChooseCourse;

        }

        //添加收费课程选课记录表
        public XcChooseCourse addChargeCourse(String userId, CoursePublish coursepublish) {

            //如果存在待支付交易记录直接返回
            LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper = queryWrapper.eq(XcChooseCourse::getUserId, userId)
                    .eq(XcChooseCourse::getCourseId, coursepublish.getId())
                    .eq(XcChooseCourse::getOrderType, "700002")//收费订单
                    .eq(XcChooseCourse::getStatus, "701002");//待支付
            List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);
            if (xcChooseCourses != null && xcChooseCourses.size()>0) {
                return xcChooseCourses.get(0);
            }

            XcChooseCourse xcChooseCourse = new XcChooseCourse();
            xcChooseCourse.setCourseId(coursepublish.getId());
            xcChooseCourse.setCourseName(coursepublish.getName());
            xcChooseCourse.setCoursePrice(coursepublish.getPrice());
            xcChooseCourse.setUserId(userId);
            xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
            xcChooseCourse.setOrderType("700002");//收费课程
            xcChooseCourse.setCreateDate(LocalDateTime.now());
            xcChooseCourse.setStatus("701002");//待支付

            xcChooseCourse.setValidDays(coursepublish.getValidDays());
            xcChooseCourse.setValidtimeStart(LocalDateTime.now());
            xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(coursepublish.getValidDays()));
              xcChooseCourseMapper.insert(xcChooseCourse);
            return xcChooseCourse;

        }

        //添加到我的课程表
        public XcCourseTables addCourseTables(XcChooseCourse xcChooseCourse) {

            //选课记录完成且未过期可以添加课程到课程表
            String status = xcChooseCourse.getStatus();
            if (!"701001".equals(status)){
                XueChengPlusException.cast("选课未成功，无法添加到课程表");
            }
            //查询我的课程表
            XcCourseTables xcCourseTables = getXcCourseTables(xcChooseCourse.getUserId(), xcChooseCourse.getCourseId());
            if(xcCourseTables!=null){
                return xcCourseTables;
            }
            XcCourseTables xcCourseTablesNew = new XcCourseTables();
            BeanUtils.copyProperties(xcChooseCourse,xcCourseTablesNew);
            xcCourseTablesNew.setChooseCourseId(xcChooseCourse.getCourseId());//记录选课表id
            xcCourseTablesNew.setCourseType(xcChooseCourse.getOrderType()); //选课类型
            xcCourseTablesNew.setUpdateDate(LocalDateTime.now());
            int insert = xcCourseTablesMapper.insert(xcCourseTablesNew);
            if (insert<0){
                XueChengPlusException.cast("选课异常");
            }
            return xcCourseTablesNew;

        }
    /**
     * @description 根据课程和用户查询我的课程表中某一门课程
     * @param userId
     * @param courseId
     * @return com.xuecheng.learning.model.po.XcCourseTables
     * @author Mr.M
     * @date 2022/10/2 17:07
     */
    public XcCourseTables getXcCourseTables(String userId,Long courseId){
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId, userId).eq(XcCourseTables::getCourseId, courseId));
        return xcCourseTables;

    }





}